package com.tanhua.server.serivce;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.Settings;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.*;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UsersService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserlikeApi userlikeApi;


    //根据用户id，查询用户资料
    public UserInfoVo findUserInfoById(Long userId) {
        //1、调用API查询
        UserInfo userInfo = userInfoApi.findById(userId);
        //2、转化为VO
        UserInfoVo vo = new UserInfoVo();
        //工具类转化
        BeanUtils.copyProperties(userInfo, vo); //将UserInfo中同名，同类型的属性，自动赋值到vo中
        //不同的，单独处理
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //更新
    public void updateUserInfo(UserInfo info) {
        userInfoApi.update(info);
    }

    //查询通用设置
    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();
        //设置id和手机号码
        vo.setId(UserHolder.getUserId());
        vo.setPhone(UserHolder.getMobile());
        //查询并设置陌生人问题
        //根据当前用户id，查询陌生人问题
        Question question = questionApi.findByUserId(UserHolder.getUserId());
        vo.setStrangerQuestion(question == null ? "你喜欢JAVA吗？" : question.getTxt());
        //查询并设置通知开关
        //根据当前用户id，查询通知开关
        Settings settings = settingsApi.findByUserId(UserHolder.getUserId());
        if (settings != null) {
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setGonggaoNotification(settings.getGonggaoNotification());
        }
        return vo;
    }

    //设置陌生人问题(保存或者更新)
    public void questions(String content) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、根据用户id，查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        //3、如果问题存在，更新
        if (question != null) {
            question.setTxt(content);
            questionApi.update(question);
        } else {
            //4、问题不存在，保存
            question = new Question();
            question.setTxt(content);
            question.setUserId(userId);
            questionApi.save(question);
        }
    }

    //设置通知开关(保存或者更新)
    public void setting(Map map) {
        Boolean like = (Boolean) map.get("likeNotification");
        Boolean pingl = (Boolean) map.get("pinglunNotification");
        Boolean gongg = (Boolean) map.get("gonggaoNotification");
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、根据用户id，查询当前用户的通知设置
        Settings settings = settingsApi.findByUserId(userId);
        //3、如果数据存在，更新
        if (settings != null) {
            settings.setGonggaoNotification(gongg);
            settings.setPinglunNotification(pingl);
            settings.setLikeNotification(like);
            settingsApi.update(settings);
        } else {
            //4、如果数据不存在，保存
            settings = new Settings();
            settings.setUserId(userId);
            settings.setGonggaoNotification(gongg);
            settings.setPinglunNotification(pingl);
            settings.setLikeNotification(like);
            settingsApi.save(settings);
        }
    }

    //分页查询黑名单数据
    public PageResult blacklist(Integer page, Integer pagesize) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用API分页查询数据：IPage
        IPage iPage = blackListApi.findByUserId(page, pagesize, userId);
        //3、将IPage中的数据内容，设置到PageResult
        PageResult vo = new PageResult(page, pagesize,
                iPage.getTotal(), iPage.getRecords());
        //4、返回
        return vo;
    }

    //删除=黑名单:根据当前用户userId和黑名单用户blackUserId
    public void delBlacklist(Long blackUserId) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用api删除
        blackListApi.delete(userId, blackUserId);
    }

    @DubboReference
    private VisitorsApi visitorsApi;
    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 分页列表
     * type
     * 1 互相关注
     * 2 我关注
     * 3 粉丝
     * 4 谁看过我
     */
    public PageResult friends(Integer type, Integer page, Integer pagesize) {
        if (type != 4) {
            //获取用户id
            Long userId = UserHolder.getUserId();
            //创建转换集合
            List<UserLike> list = new ArrayList<>();
            //判断类型
            List<UserLikeListVo> vos = new ArrayList<>();
            if (type == 1) {
                //互相喜欢
                list = userlikeApi.findEachLoveByPage(userId, page, pagesize);
                System.out.println(list);
                if (CollUtil.isEmpty(list)) {
                    return new PageResult();
                }
                //查询id集合
                List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
                //查询用户信息
                Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);

                //转换
                for (UserLike userLike : list) {
                    UserInfo userInfo = map.get(userLike.getUserId());
                    UserLikeListVo vo = UserLikeListVo.init(userInfo, userLike);
                    vos.add(vo);
                }
            }
            if (type == 2) {
                //我喜欢
                list = userlikeApi.findLoveByPage(userId, page, pagesize);
                if (CollUtil.isEmpty(list)) {
                    return new PageResult();
                }
                //查询id集合
                List<Long> userIds = CollUtil.getFieldValues(list, "likeUserId", Long.class);
                //查询用户信息
                Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);

                //转换
                for (UserLike userLike : list) {
                    UserInfo userInfo = map.get(userLike.getLikeUserId());
                    UserLikeListVo vo = UserLikeListVo.init(userInfo, userLike);
                    Boolean alreadyLove = userlikeApi.findIsFriend(userLike.getLikeUserId(), userId);
                    vo.setAlreadyLove(alreadyLove == true ? true : false);
                    vos.add(vo);
                }
            }
            if (type == 3) {
                //粉丝
                list = userlikeApi.findFanByPage(userId, page, pagesize);
                if (CollUtil.isEmpty(list)) {
                    return new PageResult();
                }
                //查询id集合
                List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
                //查询用户信息
                Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);

                //转换
                for (UserLike userLike : list) {
                    UserInfo userInfo = map.get(userLike.getUserId());
                    UserLikeListVo vo = UserLikeListVo.init(userInfo, userLike);
                    Boolean alreadyLove = userlikeApi.findIsFriend(userId, userLike.getUserId());
                    vo.setAlreadyLove(alreadyLove == true ? true : false);
                    vos.add(vo);
                }
            }
            return new PageResult(page, pagesize, 0l, vos); //实战完成
        }
        Long userId = UserHolder.getUserId();
        //调用API，根据用户id，分页查询访客列表  List<visitors>
        List<Visitors> list = visitorsApi.findAll(userId, page, pagesize);
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //提取所有的访客人信息
        List<Long> userIds = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //将List<visitors>转成 List<UserLikeListVo>
        List<UserLikeListVo> vos = new ArrayList<>();
        for (Visitors visitors : list) {
            UserInfo userInfo = map.get(visitors.getVisitorUserId());
            UserLikeListVo vo = UserLikeListVo.init(userInfo, visitors);
            vos.add(vo);
        }
        //设置查看历史访客的时间
        String key = Constants.VISITORS_USER + userId;
        Long value = System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, value.toString());
        //构造返回
        return new PageResult(page, pagesize, 0l, vos);
    }



    /**
     * 喜欢不喜欢统计数据
     *
     * @return
     */
    public UserLikeCountVo counts() {
        //1.获取userId
        Long userId = UserHolder.getUserId();
        //2.查询统计信息
        //查询喜欢信息
        List<UserLike> loveIds = userlikeApi.findLoveIdsByUserId(userId);
        //查询粉丝信息
        List<UserLike> fanIds = userlikeApi.findFanIdsByUserId(userId);
        //查询互相喜欢信息
        List<UserLike> eachLoveIds = userlikeApi.findEachLoveIdsByUserId(userId);
        //3.构造UserLikeCountVo
        UserLikeCountVo vo = new UserLikeCountVo();
        //4.转换成UserLikeCountVo对象返回
        vo.setEachLoveCount(CollUtil.isEmpty(eachLoveIds) ? 0l : new Long(eachLoveIds.size()));
        vo.setFanCount(CollUtil.isEmpty(fanIds) ? 0l : new Long(fanIds.size()));
        vo.setLoveCount(CollUtil.isEmpty(loveIds) ? 0l : new Long(loveIds.size()));
        return vo;
    }


    /**
     * 粉丝喜欢
     */
    public void fansIsLike(String uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //好友id
        Long friendId = Long.valueOf(uid);
        //查询表中是否存在
        Boolean isExist = userlikeApi.isExist(userId, friendId);
        //如果存在修改isLike
        if (isExist) {
            userlikeApi.setIsLike(friendId, userId);
        } else {
            //如果不存在进行添加
            userlikeApi.save(userId, friendId);
        }
        //查询是否为喜欢
        Boolean isLike = userlikeApi.findIsFriend(userId, friendId);
        if (isLike == null || true) {
            //添加好友关系
            friendApi.save(userId, friendId);
            //环信添加好友
            //huanXinTemplate.addContact("hx"+userId,"hx"+friendId);
        } else {
            //删除好友关系
            friendApi.delete(userId, friendId);
            //环信删除好友
            //huanXinTemplate.deleteContact("hx"+userId,"hx"+friendId);
        }
    }

    /**
     * 喜欢取消喜欢
     */
    public void setLike(String uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //好友id
        Long friendId = Long.valueOf(uid);
        //修改isLike取反
        userlikeApi.setIsLike(friendId, userId);
        //查询是否为喜欢
        Boolean isLike = userlikeApi.findIsFriend(userId, friendId);
        //添加或者删除好友关系
        if (isLike == null || isLike == true) {
            //添加好友关系
            friendApi.save(userId, friendId);
            //环信添加好友
            huanXinTemplate.addContact("hx" + userId, "hx" + friendId);
        } else {
            //删除好友关系
            friendApi.delete(userId, friendId);
            //环信删除好友
            huanXinTemplate.deleteContact("hx" + userId, "hx" + friendId);
        }
    }

    /**
     * 修改手机号，效验验证码
     */
    public Boolean checkVerificationCode(String verificationCode) {
        //获取操作用户的手机号
        String phone = UserHolder.getMobile();
        //从redis里面取出来验证码
        String code = redisTemplate.opsForValue().get("Code_" + phone);
//        System.err.println("code="+code);
//        System.err.println("verificationCode="+verificationCode);
        //判断验证码是否一致
        if (StringUtils.isEmpty(code) || !verificationCode.equals(code)) {
            //不一致返回false
            return false;
        } else {
            //一直返回true
            return true;
        }
    }

    //修改手机号 - 3 保存
    public void phone(String phone) {
        //通过当前登录手机号
        String mobile = UserHolder.getMobile();
        //通过当前登录手机号取出用户对象
        User user = userApi.findByMobile(mobile);
        //将新手机号设置给用户对象
        user.setMobile(phone);
        //调用Api层将用户数据修改
        userApi.update(user);
    }
}
